package com.lyh.hkcloud.util.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapUtil {

    public static String getString(List<Map<String, Object>> list, int index, String name) {
        return getString(list, index, name, "");
    }

    public static String getString(List<Map<String, Object>> list, int index, String name, String defaultValue) {
        if (list == null || list.isEmpty() || list.size() < index + 1) {
            return defaultValue;
        }
        return getString(list.get(index), name, defaultValue);
    }

    public static String getString(Map<String, Object> map, String name) {
        return getString(map, name, "");
    }

    public static String getString(Map<String, Object> map, String name, String defaultValue) {
        if (map.containsKey(name)) {
            return StringUtils.toString(map.get(name), defaultValue);
        }
        return defaultValue;
    }

    public static int getInt(Map<String, Object> map, String name) {
        return getInt(map, name, 0);
    }

    public static int getInt(Map<String, Object> map, String name, int defaultValue) {
        if (map.containsKey(name)) {
            return StringUtils.toInt(map.get(name), defaultValue);
        }
        return defaultValue;
    }

    public static float getFloat(Map<String, Object> map, String name, float defaultValue) {
        if (map.containsKey(name)) {
            return StringUtils.toFloat(map.get(name), defaultValue);
        }
        return defaultValue;
    }

    public static float getFloatOf0Else(Map<String, Object> map, String name, float defaultValue) {
        if (map.containsKey(name)) {
            if (StringUtils.toFloat(map.get(name), 0) > 0) {
                return StringUtils.toFloat(map.get(name), defaultValue);
            }
        }
        return defaultValue;
    }

    public static Map<String, Object> clone(Map<String, Object> map) {
        Map<String, Object> value = new HashMap<>();
        if (map != null) {
            Set<String> keys = map.keySet();
            for (String key : keys) {
                value.put(key, map.get(key));
            }
        }
        return value;
    }

    public static String getStringOfNullElse(Map<String, Object> map, String key, String elseKey) {
        if (StringUtils.isNotEmpty(getString(map, key))) {
            return getString(map, key);
        }
        return getString(map, elseKey);
    }

    public static String getStringOfNullOr0Else(Map<String, Object> map, String key, String elseKey) {
        if (getFloat(map, key, 0) > 0) {
            return getString(map, key);
        }
        return getString(map, elseKey);
    }
}
